<template>
  <div>
    <!-- :inline="true" 表单一行显示 -->
    <el-form ref="searchForm" :inline="true" :model="searchMap" style="margin-top: 20px">
      <!-- 重置会看 el-form-item 组件元素的 prop 上是否指定了字段名，指定了才会重置生效 -->
      <el-form-item prop="avdId">
        <el-input v-model="searchMap.avdId" placeholder="广告ID" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item prop="avdName" v-if="!isDialog">
        <el-input v-model="searchMap.avdName" placeholder="广告名称" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item prop="avdType" v-if="!isDialog">
        <el-input v-model="searchMap.avdType" placeholder="广告类型" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
        <el-button v-if="!isDialog" @click="resetForm('searchForm')">重置</el-button>
        <el-button v-if="!isDialog" type="primary" @click="handleImageAdd">添加图片广告</el-button>
        <el-button v-if="!isDialog" type="primary" @click="handleVideoAdd">添加视频广告</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :highlight-current-row="isDialog"
      @current-change="clickCurrentChange"
      :data="list"
      height="580"
      border
      style="width: 100%"
    >
      <!-- type="index"获取索引值，从1开始 ，label显示标题，prop 数据字段名，width列宽 -->
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
      <el-table-column prop="avdId" label="广告ID" align="center"></el-table-column>
      <el-table-column prop="avdName" label="广告名称" align="center"></el-table-column>
      <el-table-column v-if="!isDialog" prop="avdType" label="广告类型" align="center" :formatter = "deviceAvdTypeFormat"></el-table-column>
      <el-table-column v-if="!isDialog" prop="description" label="广告描述" align="center"></el-table-column>
      <el-table-column v-if="!isDialog" prop="createTime" label="添加时间" align="center" :formatter = "timeFormat"></el-table-column>
      <!-- <el-table-column v-if="!isDialog" label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :layout="!isDialog ? 'total, sizes, prev, pager, next, jumper': 'prev, pager, next'"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      :total="total"
    ></el-pagination>

    <el-dialog v-if="!isDialog" title="广告添加" :visible.sync="dialogFormVisible" width="500px">
      <el-form
        :rules="rules"
        ref="pojoForm"
        label-width="100px"
        label-position="right"
        style="width: 400px;"
        :model="pojo"
      >
        <el-form-item label="上传图片" :label-width="formLabelWidth" prop="file">
          <el-upload
            ref="upload"
            action="#"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            list-type="picture-card"
            multiple
            :data="pojo"
            :limit=limitNum
            :auto-upload="false"
            :on-exceed="handleExceed"
            :before-upload="handleBeforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :http-request="fileRequest">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="广告名称" prop="avdName">
          <el-input v-model="pojo.avdName"></el-input>
        </el-form-item>
        <el-form-item label="广告描述" prop="description">
          <el-input v-model="pojo.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- <el-button
          type="primary"
          @click="pojo.id === null ? addData('pojoForm'): updateData('pojoForm')"
        >确 定</el-button> -->
        <el-button size="small" type="primary" @click="uploadFile('upload')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="!isDialog" title="广告添加" :visible.sync="dialogFormVideoVisible" width="500px">
      <el-form
        :rules="rules"
        ref="pojoForm"
        label-width="100px"
        label-position="right"
        style="width: 400px;"
        :model="pojo"
      >
        <el-form-item label="上传视频" :label-width="formLabelWidth" prop="file">
          <el-upload
            ref="upload"
            action="#"
            accept="video/mp4,vido/ogg,video/avi,video/flv"
            list-type="picture-card"
            multiple
            :data="pojo"
            :limit=limitNum
            :auto-upload="false"
            :on-exceed="handleExceed"
            :before-upload="handleVideoBeforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :http-request="fileVideoRequest">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="广告名称" prop="avdName">
          <el-input v-model="pojo.avdName"></el-input>
        </el-form-item>
        <el-form-item label="广告描述" prop="description">
          <el-input v-model="pojo.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- <el-button
          type="primary"
          @click="pojo.id === null ? addData('pojoForm'): updateData('pojoForm')"
        >确 定</el-button> -->
        <el-button size="small" type="primary" @click="uploadFile('upload')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import advertApi from "@/api/advert";
import {formatDate} from "@/api/date";

export default {
  props: {
    // 接收父组件传递过来 的数据,通过isDialog来判断 是否为弹框
    // 如果为 true, 则是弹框, false 就是列表
    isDialog: Boolean
  },

  data() {
    return {
      limitNum: 2,
      // formLabelWidth: '80px',
      fileList: [],

      list: [],
      pageSize: 10, // 每页显示条数 10条
      currentPage: 1, // 当前页码
      total: 0, // 总记录数
      searchMap: {
        avdId: "",
        avdName: "",
        avdType: ""
      }, // 条件查询的绑定字段值
      dialogFormVisible: false,
      dialogFormVideoVisible:false,
      pojo: {
        avdName: "",
        description: "",
      },
      rules: {
        name: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
        linkman: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ]
      }
    };
  },

  components: {},
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      // supplierApi.getList().then(response => {
      advertApi
        .search(this.currentPage, this.pageSize, this.searchMap)
        .then(response => {
          const data = response.data.data;
          this.list = data.rows;
          this.total = data.total;
          console.log("list:"+this.list+",total:"+this.total);
        });
    },

    // 当每页显示条数改变后，进行调用该方法,val是当前改变后条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 打开新增窗口
    handleImageAdd() {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["pojoForm"].resetFields();
        this.$refs["upload"].resetFields();
      });
    },
    handleVideoAdd(){
      this.dialogFormVideoVisible = true;
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["pojoForm"].resetFields();
        this.$refs["upload"].resetFields();
      });
    },
    // 提交新增表单
    addData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //提交表单
          advertApi.add(this.pojo).then(response => {
            const resp = response.data;
            if (resp.flag) {
              this.fetchData();
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: resp.message,
                type: "warning"
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    // 提交表单
    uploadFile(formName){
      this.$refs[formName].submit();
      // this.$refs[formName].validate(valid => {
      //   if (valid) {
      //     console.log("pojo:"+this.pojo.file)
      //     //提交表单
      //     advertApi.add(this.pojo).then(response => {
      //       const resp = response.data;
      //       if (resp.flag) {
      //         this.fetchData();
      //         this.dialogFormVisible = false;
      //       } else {
      //         this.$message({
      //           message: resp.message,
      //           type: "warning"
      //         });
      //       }
      //     });
      //   }
      // });
    },

    fileRequest(item){
      let uploadData = new FormData();
      uploadData.append('file',item.file);
      uploadData.append('avdName',this.pojo.avdName);
      uploadData.append('description',this.pojo.description);
      advertApi.add(uploadData).then(response =>{
          const resp = response.data;
          if (resp.flag) {
            this.fetchData();
            this.dialogFormVisible = false;
          } else {
            this.$message({
              message: resp.message,
              type: "warning"
            });
          }
      })
    },

    fileVideoRequest(item){
      let uploadData = new FormData();
      uploadData.append('file',item.file);
      uploadData.append('avdName',this.pojo.avdName);
      uploadData.append('description',this.pojo.description);
      advertApi.add(uploadData).then(response =>{
          const resp = response.data;
          if (resp.flag) {
            this.fetchData();
            this.dialogFormVideoVisible = false;
          } else {
            this.$message({
              message: resp.message,
              type: "warning"
            });
          }
      })
    },

    //打开编辑窗口
    handleEdit(id) {
      // console.log('编辑', id)
      // 清除原来的表单数据和校验结果
      this.handleAdd();
      advertApi.getById(id).then(response => {
        const resp = response.data;
        if (resp.flag) {
          this.pojo = resp.data;
        } else {
          //提示获取数据失败
          this.$message({
            message: resp.message,
            type: "warning"
          });
        }
      });
    },

    updateData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 页面校验通过,才可发送请求进行更新
          advertApi.update(this.pojo).then(response => {
            const resp = response.data;
            if (resp.flag) {
              // 更新成功,刷新数据,关闭窗口
              this.fetchData();
              this.dialogFormVisible = false;
            } else {
              //提示更新失败
              this.$message({
                message: resp.message,
                type: "warning"
              });
            }
          });
        } else {
          return false;
        }
      });
    },

    handleDelete(id) {
      console.log("删除", id);
      this.$confirm("确认删除这条记录吗?", "提示", {
        confirmButtonText: "确认",
        cancleButtonText: "取消"
      })
        .then(() => {
          advertApi.deleteById(id).then(response => {
            const resp = response.data;
            //提示更新失败
            this.$message({
              message: resp.message,
              type: resp.flag ? "success" : "error"
            });

            if (resp.flag) {
              // 删除成功,刷新数据
              this.fetchData();
            }
          });
        })
        .catch(() => {
          // 取消删除
        });
    },
    // 当点击某一行时,会调用这个函数进行处理
    clickCurrentChange(currentRow) {
      console.log("子组件", currentRow);
      // 点击后,要将点击的数据传递到父组件(商品管理中),
      // 则可以通过触发父组件中的option-supplier, 触发之后 ,
      //父组件可以在 option-supplier 这个事件对应的处理函数中进行接收数据currentRow
      this.$emit("option-supplier", currentRow);
    },
    //转变设备类型数据
    deviceAvdTypeFormat(row, column){
      if(row.avdType == 1) {
        return '图片广告';
      }else if(row.avdType == 2){
        return '视频广告';
      }
    },
    timeFormat(row, column){
      let date = new Date(row.createTime)
      return formatDate(date, 'yyyy-MM-dd hh:mm')
    },
    // 上传文件之前的钩子
    handleBeforeUpload(file){
      console.log('before')
      if(!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
        })
      }
      let size = file.size / 1024 / 1024 / 2
      if(size > 10) {
        this.$notify.warning({
          title: '警告',
          message: '图片大小必须小于10M'
        })
      }
    },
    handleVideoBeforeUpload(file){
      console.log('before')
      if(!(file.type === 'video/mp4' || file.type === 'video/ogg' || file.type === 'video/flv' || file.type === 'video/avi')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为video/mp4, video/ogg, video/flv, video/avi的视频'
        })
      }
      let size = file.size / 1024 / 1024 / 2
      if(size > 100) {
        this.$notify.warning({
          title: '警告',
          message: '视频大小必须小于100M'
        })
      }
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {

    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  }
};
</script>

<style scoped>
  
</style>